package com.vvlive.caibao.smartcity.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.vvlive.caibao.smartcity.bean.MyLocationBean;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Random;

/**
 * Created by lenovo on 2015/6/29.
 * 定位工具类
 * 需要实例化该类,并且实现接口GetMyLocation
 */
@SuppressWarnings("ALL")
public class MyLocationUtil implements AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {
    private LocationManagerProxy mLocationManagerProxy;
    private Random mRandom = new Random();
    GetMyLocation mGetMyLocation;
    Context context;
    MyLocationBean myLocationBean;
    //地图搜索
    private LatLonPoint latLonPoint;
    GeocodeSearch geocoderSearch;
    private Handler handler = new Handler();
    /**
     * MyLocationUtil（context，this）
     * */
    public MyLocationUtil(Context context, GetMyLocation mGetMyLocation){
        this.context = context;
        this.mGetMyLocation = mGetMyLocation;
        init();
        Log.i("Location", sHA1(context));

    }
    /**
     * 初始化定位
     */
    private void init() {
//        int randomTime = mRandom.nextInt(1000);
        // 初始化定位，只采用网络定位
        mLocationManagerProxy = LocationManagerProxy.getInstance(context);
//        mAMapLocManager.setGpsEnable(false);
        mLocationManagerProxy.setGpsEnable(true);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用destroy()方法
        // 其中如果间隔时间为-1，则定位只定一次,
        // 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
        mLocationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, 6 * 1000, 15, this);

//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(context,"定位超时",Toast.LENGTH_SHORT).show();
//            }
//        }, 12000);// 设置超过12秒还没有定位到就停止定位

    }
    /**
     * 销毁定位
     *
     * */
    private void close_l(){
        // 移除定位请求
        if (mLocationManagerProxy != null) {
            // 注意更换定位时间后，需要先将定位请求删除，再进行定位请求
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destory();
        }
        mLocationManagerProxy = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.i("定位","aMapLocation"+aMapLocation.getAddress());
        if (aMapLocation != null
                && aMapLocation.getAMapException().getErrorCode() == 0) {
            // 定位成功回调信息，设置相关消息

            myLocationBean = new MyLocationBean();
            myLocationBean.setLatitude(aMapLocation.getLatitude());
            myLocationBean.setLongitude(aMapLocation.getLongitude());
            myLocationBean.setRoad(aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getRoad());
            myLocationBean.setDes(aMapLocation.getAddress());
            //反编码
            latLonPoint = new LatLonPoint(myLocationBean.getLatitude(), myLocationBean.getLongitude());
            fanbianma();
            Log.i("定位成功", "定位成功--混合定位" + aMapLocation.getLatitude() + aMapLocation.getLongitude() + "\n" +
                    String.valueOf(aMapLocation.getAccuracy()) + "\n" +
                    aMapLocation.getAddress() + "\n" +
                    aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getRoad() + "\n" +
                    aMapLocation.getExtras()+"\n"+
                    aMapLocation.getStreet());
            this.close_l();
        } else {
            Log.e("AmapErr", "Location ERR1:" + aMapLocation.getAMapException().getErrorCode());
            Log.e("AmapErr", "Location ERR2:" + aMapLocation.getAMapException().toString());
            Log.e("AmapErr", "Location ERR3:" + aMapLocation.getAMapException().toString());
            Log.e("AmapErr", "Location ERR:" + aMapLocation.getAMapException().getErrorMessage().toString());
            Log.e("AmapErr", "Location ERR:" + aMapLocation.getAMapException().getLocalizedMessage().toString());
        }
    }
    /**
     * 地理反编码
     * 获取详细地址
     * */
    public void fanbianma(){
        Log.i("地理逆编码","地理编码");
        geocoderSearch = new GeocodeSearch(context);
        geocoderSearch.setOnGeocodeSearchListener(this);
        //latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }
     @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Double geoLat = location.getLatitude();
            Double geoLng = location.getLongitude();
            String str = ("定位成功:(" + geoLng + "," + geoLat + ")"
                    + "\n精    度    :" + location.getAccuracy() + "米"
                    + "\n定位方式:" + location.getProvider() + "\n定位时间:");
            Log.i("定位测试....","str");
        }else{
            Log.i("定位测试....", "失败失败失败失败");
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
    /**
     * 地理反编码
     * */
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        Log.i("地理反编码返回",regeocodeResult.getRegeocodeAddress().getFormatAddress());
        myLocationBean.setFormatAddress(regeocodeResult.getRegeocodeAddress().getFormatAddress());
        mGetMyLocation.MyLocation(myLocationBean);
    }
    /**
     * 地理编码
     * */
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    /**
     * 定位回调接口
     * */
    public interface GetMyLocation{
        void MyLocation(MyLocationBean myLocationBean);
    }
    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);

            byte[] cert = info.signatures[0].toByteArray();

            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                                              .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            return hexString.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
